#ifndef MODBUSHELP_H
#define MODBUSHELP_H

#include <QObject>
#include <QVector>
#include <QVariant>

#include <QThread>
#include <QSerialPort>
#include <QModbusDevice>
#include <QModbusRtuSerialMaster>
#include <QModbusDataUnit>
#include <QModbusReply>
#include <QEventLoop>
#include <QFile>
#include <QTextStream>

class ModbusHelp : public QObject
{
    Q_OBJECT
public:
    explicit ModbusHelp(QObject *parent = nullptr);

    ~ModbusHelp();

    ///
    /// \brief setModbusMisc
    /// \param name
    /// \param baudrate
    /// \param slaveId
    ///设置 modbus 通信参数
    void setModbusMisc(const QString & name,int baudrate,int slaveId);


    volatile bool opsIsOK;    //操作是否成功
    volatile bool cancelOps;    //取消本次操作

signals:

    ///
    /// \brief operatePercent
    /// \param p
    ///发送当前操作的 进行百分比
    void operatePercent(int p);

    ///
    /// \brief operateVerifyFailed
    ///当前操作 验证失败
    void operateVerifyFailed();

public slots:

    ///
    /// \brief sendDataToHoldRegs
    /// \param addr
    /// \param data
    /// \param scale
    /// \return
    ///将 data 数据乘以scale 转换为无符号16进制数据 发送addr地址开始的保持寄存器里 成功返回true
    /// dataptr是 QVector<double>指针 在本函数内进行释放
    void sendDataToHoldRegs(quint16 addr,void* dataptr,double scale);

    ///
    /// \brief readHoldRegsToCSV
    /// \param filename
    /// \param addr
    /// \param len
    ///读取modbus一批保持寄存器 保存到filename CSV文件
    void readHoldRegsToCSV(const QString &filename,quint16 addr,int len);

private slots:

    ///
    /// \brief onThreadStarted
    ///modbus 访问线程启动
    void onThreadStarted();

    ///
    /// \brief onThreadFinish
    ///modbus 访问线程结束
    void onThreadFinish();

private:

    QThread *m_thread;  //modbus 访问线程

    QModbusRtuSerialMaster *m_modbus;  //modbus 设备
    QString m_modbus_port;  //串口名
    int m_modbus_baudrate; //波特率
    int m_modbus_slaveID;   //modbus ID

};

#endif // MODBUSHELP_H
